package core

import (
	"context"
	"fmt"
	"github.com/hdt3213/delayqueue"
	"github.com/redis/go-redis/v9"
	"github.com/sirupsen/logrus"
	"github.com/smartwalle/alipay/v3"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/models/ctype"
)

type TradeCloseRsp struct {
	Error      error
	OutTradeNo string `json:"out_trade_no"`
	TradeNo    string `json:"trade_no"`
}

func InitRedisDelayQueue(client *redis.Client) {

	var aliclient, err = InitAlipayClient()
	if err != nil {
		logrus.Error("初始化阿里支付失败")
		return
	}
	queue := delayqueue.NewQueue("order_delay_queue", client, func(no string) bool {

		// 处理订单失效
		var order models.OrderModel
		err := global.DB.Take(&order, "no = ?", no).Error
		if err != nil {
			logrus.Error(err)
			return true
		}
		//主动告诉ali取消这个订单,如果交易成功,则阿里返回不支持这个操作
		result, _ := aliclient.TradeClose(context.Background(), alipay.TradeClose{
			OutTradeNo: no,
		})
		// 读取响应体,不重要,可以我们主动告诉阿里的时候,阿里已经1min结束了这个订单了
		fmt.Println("主动取消订单Ali回复:", result)
		if order.PayStatus == ctype.UnpaidPayStatus {
			global.DB.Model(&order).Update("pay_status", ctype.TimeoutPayStatus)
		}
		return true
	})
	global.OrderDelayQueue = queue
	queue.StartConsume()
}
